package work_space;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

public class Order {
    private List<Drink> drinkList;

    private String clientName;

    public OrderStatus getOrderStatus() {
        return orderStatus;
    }

    private volatile OrderStatus orderStatus;

    public void setClientName(String clientName) {
        this.clientName = clientName;
    }

    public void setOrderStatus(OrderStatus orderStatus) {
        this.orderStatus = orderStatus;
    }

    public boolean tryFinish() {
        boolean isFinished = drinkList.stream().allMatch(drink -> drink.getStatus().equals(DrinkStatus.FINISHED));
        if (isFinished) {
            // 如果全部都完成了,就执行状态更新
            this.orderStatus = OrderStatus.FINISHED;
        }
        return isFinished;
    }


    public Order() {
        this.drinkList = Collections.synchronizedList(new ArrayList<>());
    }

    public List<Drink> getDrinkList() {
        return drinkList;
    }

    public long getTeaCount() {
        return this.drinkList.stream().filter(item -> item.getDrinkType().equals(DrinkType.TEA)).count();
    }

    public long getCoffeeCount() {
        return this.drinkList.stream().filter(item -> item.getDrinkType().equals(DrinkType.COFFEE)).count();
    }

    public long getTotalItems() {
        return this.drinkList.size();
    }

    public void setDrinkList(List<Drink> drinkList) {
        this.drinkList = drinkList;
    }

    public void addOrder(Order newOrder) {
        this.drinkList.addAll(newOrder.getDrinkList());
    }

    public Boolean isFinish() {
        return this.orderStatus.equals(OrderStatus.FINISHED) && drinkList
                .stream()
                .allMatch(item -> item.getStatus().equals(DrinkStatus.FINISHED));
    }

    public Boolean hasCoffee() {
        return drinkList.stream().anyMatch(item -> item.getDrinkType().equals(DrinkType.COFFEE));
    }

    public Boolean hasTea() {
        return drinkList.stream().anyMatch(item -> item.getDrinkType().equals(DrinkType.TEA));
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();

        // 标题
        sb.append("Virtual Caffee Order As Follow\n");
        sb.append("┌────────────────────────────────┐\n");

        // 客户信息
        sb.append("│ 👤  Client: ").append(padRight(clientName, 20)).append("│\n");
        sb.append("│ 📊  Status: ").append(padRight(formatOrderStatus(orderStatus), 20)).append("│\n");
        sb.append("├────────────────────────────────┤\n");

        // 饮品统计
        if (drinkList != null && !drinkList.isEmpty()) {
            long teaTotal = drinkList.stream().filter(d -> d.getDrinkType() == DrinkType.TEA).count();
            long coffeeTotal = drinkList.stream().filter(d -> d.getDrinkType() == DrinkType.COFFEE).count();

            long teaFinished = drinkList.stream()
                                        .filter(d -> d.getDrinkType() == DrinkType.TEA && d.getStatus() == DrinkStatus.FINISHED)
                                        .count();
            long coffeeFinished = drinkList.stream()
                                           .filter(d -> d.getDrinkType() == DrinkType.COFFEE && d.getStatus() == DrinkStatus.FINISHED)
                                           .count();

            sb.append("│          Drink Summary          │\n");

            // 茶的状态
            if (teaTotal > 0) {
                String teaStatus = getProgressBar(teaFinished, teaTotal) + " " + teaFinished + "/" + teaTotal;
                sb.append("│ 🍵  Tea:    ").append(padRight(teaStatus, 18)).append("│\n");
            }

            // 咖啡的状态
            if (coffeeTotal > 0) {
                String coffeeStatus = getProgressBar(
                        coffeeFinished, coffeeTotal) + " " + coffeeFinished + "/" + coffeeTotal;
                sb.append("│ ☕  Coffee: ").append(padRight(coffeeStatus, 18)).append("│\n");
            }

            sb.append("├────────────────────────────────┤\n");

            // 详细列表
            sb.append("│          Drink Details          │\n");
            int teaNum = 1, coffeeNum = 1;
            for (Drink drink : drinkList) {
                String drinkIcon = (drink.getDrinkType() == DrinkType.TEA) ? "🍵" : "☕";
                String drinkName = (drink.getDrinkType() == DrinkType.TEA) ? "Tea " + teaNum++ : "Coffee " + coffeeNum++;
                String statusIcon = getStatusIcon(drink.getStatus());

                sb.append("│ ").append(drinkIcon).append(" ")
                  .append(padRight(drinkName, 10))
                  .append(statusIcon).append(" ")
                  .append(padRight(formatDrinkStatus(drink.getStatus()), 12))
                  .append("│\n");
            }
        } else {
            sb.append("│         No drinks ordered        │\n");
        }

        sb.append("├────────────────────────────────┤\n");

        // 总结信息
        String summary = getOrderSummary();
        sb.append("│ ").append(padRight(summary, 30)).append("│\n");

        sb.append("└────────────────────────────────┘");

        return sb.toString();
    }

    private String formatOrderStatus(OrderStatus status) {
        return switch (status) {
            case WAITING -> "⏳ Waiting";
            case PROCESSING -> "🔥 Preparing";
            case FINISHED -> "✅ Finished";
        };
    }

    private String formatDrinkStatus(DrinkStatus status) {
        return switch (status) {
            case WAITING -> "Waiting";
            case BREWING -> "Brewing";
            case FINISHED -> "Ready";
        };
    }

    private String getStatusIcon(DrinkStatus status) {
        return switch (status) {
            case WAITING -> "⏰";
            case BREWING -> "🔥";
            case FINISHED -> "✅";
        };
    }

    private String getProgressBar(long finished, long total) {
        if (total == 0) return "[░░░░░░░░░░]";

        int percentage = (int) ((finished * 10) / total);
        StringBuilder bar = new StringBuilder("[");
        for (int i = 0; i < 10; i++) {
            bar.append(i < percentage ? "█" : "░");
        }
        bar.append("]");
        return bar.toString();
    }

    private String getOrderSummary() {
        if (drinkList == null || drinkList.isEmpty()) {
            return "📝 Empty order";
        }

        long total = drinkList.size();
        long finished = drinkList.stream()
                                 .filter(drink -> drink.getStatus() == DrinkStatus.FINISHED)
                                 .count();

        if (finished == total) {
            return "🎉 Ready for collection!";
        } else if (finished > 0) {
            return "📈 Partially completed";
        } else {
            return "⏳ Still preparing...";
        }
    }

    private String padRight(String s, int n) {
        return String.format("%-" + n + "s", s);
    }
}
